package com.example.demo.core.util;/**
 * Created by kete on 2017-10-30.
 */

import com.example.demo.common.exception.EbsException;
import com.example.demo.common.persistence.util.JsonUtil;
import com.example.demo.common.vo.ShiroUser;
import com.example.demo.core.cache.CacheManager;
import com.example.demo.core.support.StrKit;
import com.xiaoleilu.hutool.crypto.digest.DigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 作者：kete
 * 创建时间：2017-10-30 16:10
 * 功能描述：
 * 版本：
 */
public class UserUtil {

    private static Logger logger = LoggerFactory.getLogger(UserUtil.class);

    public static String accessToken = "accessToken";

    public static String fileTokenKey = "f_t";

    public static String fileTokenRequestKey = "f_t_request_attribute";

    public static long userTokenTime = 60 * 60 * 2;

    /**
     * 有效30分钟
     */
    public static int userCookieTime = 60 * 60;



    public static String createFileToken() {
        String fileToken = UserUtil.getCookie(UserUtil.fileTokenKey);
        if (StrKit.isEmpty(fileToken)) {
            Object attribute = WebUtil.getRequest().getAttribute(UserUtil.fileTokenRequestKey);
            if (null == attribute || StrKit.isEmpty(attribute.toString())) {
                UUID uuid = UUID.randomUUID();
                fileToken = DigestUtil.sha1Hex(uuid.toString());
            } else {
                fileToken = attribute.toString();
            }

            WebUtil.getRequest().setAttribute(UserUtil.fileTokenRequestKey, fileToken);
            UserUtil.addCookie(UserUtil.fileTokenKey, fileToken);
        }

        return fileToken;
    }

    public static String setUser(ShiroUser user,String accessToken){
        logger.info("accessToken=" + accessToken);
        String strJson = JsonUtil.toJSon(user);
        if(StrKit.isEmpty(accessToken)){
            UUID uuid = UUID.randomUUID();
            accessToken = uuid.toString();
        }
        CacheManager.set(accessToken,strJson,userTokenTime);

        return accessToken;

    }
    public static ShiroUser getUser(String accessToken){

        try {
            if (StrKit.isEmpty(accessToken))
                accessToken = getAccessToken();

            if (StrKit.isNotEmpty(accessToken)) {
                String userInfoJson = CacheManager.get(accessToken);
                if(StrKit.isNotEmpty(userInfoJson)){
                    ShiroUser user = JsonUtil.toBean(userInfoJson,ShiroUser.class);
                    if(user!=null&&null!=user.getId()){
                        return user;
                    }
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return null;

    }

    public static Integer getUserId(String accessToken) {
        ShiroUser userInfo = getUser(accessToken);
        if (null != userInfo) {
            return userInfo.getId();
        }
        return null;
    }

    public static Integer getOrgId(String accessToken) {
        ShiroUser userInfo = getUser(accessToken);
        if (null != userInfo) {
            return -1;
        }
        return -1;
    }

    public static  void addCookie(String cookieName, String cookieValue){
        addCookie(cookieName,cookieValue,UserUtil.userCookieTime);
    }

    public static void addCookie(String cookieName, String cookieValue, int expiry) {

        if (StrKit.isEmpty(cookieName)) return;

        HttpServletResponse response = WebUtil.getResponse();
        try {
            Cookie cookie = new Cookie(cookieName, URLEncoder.encode(cookieValue, "UTF-8"));
            cookie.setMaxAge(expiry);
            cookie.setPath("/");
            WebUtil.cookieSetDomain(cookie);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            logger.info(e.getMessage());
        }
    }


    public static String getCookie(String cookieName) {

        if (StrKit.isEmpty(cookieName)) return "";

        HttpServletRequest request = WebUtil.getRequest();

        Cookie[] cookies = request.getCookies();
        if (cookies == null) return "";

        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return "";
    }

    public static void removeCookie(String cookieName) {

        Cookie username = new Cookie(cookieName, "");
        username.setMaxAge(0);
        username.setPath("/");
        WebUtil.cookieSetDomain(username);
        HttpServletResponse response = WebUtil.getResponse();
        response.addCookie(username);
    }


    public static String getAccessToken() {
        String accessToken = getCookie(UserUtil.accessToken);
        //logger.info(">>>>>user login token = " + accessToken);
        String uuid = CacheManager.get(accessToken + "_uuid");
        boolean check = WebUtil.checkAccessTokenSignature(accessToken, uuid);
        if (!check) {
            throw new EbsException("登录异常！");
        }
        return accessToken;
    }

    public static String createAccessToken() {

        String uuid = UUID.randomUUID().toString();
        String accessToken = WebUtil.getAccessTokenSignature(uuid);
        CacheManager.set(accessToken + "_uuid", uuid);

        return accessToken;
    }

}
